import requests
import json
import logging
from java.util import HashMap
from java.lang import String, Exception as JavaException
from com.inductiveautomation.ignition.common import BasicDataset

"""
created by ai
"""

class SAPApi:
    def __init__(self, base_url, username, password):
        self.base_url = base_url
        self.username = username
        self.password = password
        self.session = requests.Session()
        self.session.auth = (self.username, self.password)
        self.headers = HashMap()
        self.headers.put("Content-Type", "application/json")
        self.headers.put("Accept", "application/json")
        self.logger = system.util.getLogger("SAPApi")

    def login(self):
        """登录SAP系统获取token"""
        try:
            url = self.base_url + "/auth/login"
            response = system.net.httpPost(url, self.headers, "", self.username, self.password)
            if response.getStatusCode() == 200:
                responseMap = system.util.jsonDecode(response.getBody())
                token = responseMap.get('token')
            if token:
                self.headers.put("Authorization", "Bearer " + token)
                self.logger.info("成功登录SAP系统")
                return True
            return False
        except JavaException as e:
            self.logger.error("登录SAP系统失败: %s" % str(e))
            return False

    def get_material_master_data(self, material_id):
        """获取物料主数据"""
        try:
            url = self.base_url + "/api/material/" + material_id
            response = system.net.httpGet(url, self.headers)
            if response.getStatusCode() == 200:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("获取物料主数据失败: %s" % str(e))
            return None

    def create_sales_order(self, order_data):
        """创建销售订单"""
        try:
            url = self.base_url + "/api/sales_orders"
            jsonData = system.util.jsonEncode(order_data)
            response = system.net.httpPost(url, self.headers, jsonData)
            if response.getStatusCode() == 200 or response.getStatusCode() == 201:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("创建销售订单失败: %s" % str(e))
            return None

    def get_purchase_orders(self, filter_params=None):
        """获取采购订单列表"""
        try:
            url = self.base_url + "/api/purchase_orders"
            params = HashMap()
            if filter_params:
                for key, value in filter_params.items():
                    params.put(key, value)
            response = system.net.httpGet(url, self.headers, params)
            if response.getStatusCode() == 200:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("获取采购订单失败: %s" % str(e))
            return None

    def create_goods_receipt(self, receipt_data):
        """创建收货单"""
        try:
            url = self.base_url + "/api/goods_receipts"
            jsonData = system.util.jsonEncode(receipt_data)
            response = system.net.httpPost(url, self.headers, jsonData)
            if response.getStatusCode() == 200 or response.getStatusCode() == 201:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("创建收货单失败: %s" % str(e))
            return None

    def get_inventory_data(self, plant_id=None, storage_location=None):
        """获取库存数据"""
        try:
            params = HashMap()
            if plant_id:
                params.put("plant", plant_id)
            if storage_location:
                params.put("storage_location", storage_location)

            url = self.base_url + "/api/inventory"
            response = system.net.httpGet(url, self.headers, params)
            if response.getStatusCode() == 200:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("获取库存数据失败: %s" % str(e))
            return None

    def create_production_order(self, production_data):
        """创建生产订单"""
        try:
            url = self.base_url + "/api/production_orders"
            jsonData = system.util.jsonEncode(production_data)
            response = system.net.httpPost(url, self.headers, jsonData)
            if response.getStatusCode() == 200 or response.getStatusCode() == 201:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("创建生产订单失败: %s" % str(e))
            return None

    def get_customer_data(self, customer_id):
        """获取客户主数据"""
        try:
            url = self.base_url + "/api/customers/" + customer_id
            response = system.net.httpGet(url, self.headers)
            if response.getStatusCode() == 200:
                return system.util.jsonDecode(response.getBody())
            return None
        except JavaException as e:
            self.logger.error("获取客户主数据失败: %s" % str(e))
            return None